package com.xcb.spring.util;

import org.objectweb.asm.ClassReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    public static List<Class<?>> findClassToDirectory(File file,ClassLoader classLoader) {
        List<Class<?>> classList = new ArrayList<Class<?>>(30);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if(f.isDirectory()){
                    classList.addAll(findClassToDirectory(f,classLoader));
                }
                if(!f.canRead()){
                    log.error("{},file not permission",f.getPath());
                    continue;
                }
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    try(InputStream iso = new FileInputStream(f)){
                        ClassReader classReader = new ClassReader(iso);
                        String className = classReader.getClassName();
                        className = className.replaceAll("/",".").replaceAll("\\\\",".");
                        Class<?> clazz = classLoader.loadClass(className);
                        classList.add(clazz);
                        classReader = null;
                    }catch (Exception e){
                        log.error("exception,",e);
                    }
                }
            }
        }
        return classList;
    }
}
